#pragma once
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <netinet/in.h>
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <functional>

typedef std::function<std::string(const std::string &)> func_t;

Log lg;

const uint16_t defaultport = 8080;
const std::string defaultip = "0.0.0.0";

const int size = 1024;

class UdpServe
{
public:
  UdpServe(uint16_t port = defaultport, std::string ip = defaultip) : _socketfd(0), _port(port), _ip(ip), _isRuning(false)
  {
  }

  void Init()
  {
    // 1. 创建 socket
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
      lg(Fatal, "socketfd create failed, error: %s", strerror(errno));
      exit(1);
    }
    lg(Info, "socket create success, socketfd: %d, errmsg: %s", socketfd, strerror(errno));
    _socketfd = socketfd;

    // 2. 绑定(bind) socket

    // 先创建一个本地的结构体
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(_port);
    local.sin_addr.s_addr = inet_addr(_ip.c_str());

    // 绑定端口号服务器
    int bret = bind(_socketfd, (const sockaddr *)&local, sizeof(local));
    if (bret < 0)
    {
      lg(Fatal, "bind port&ip failed, error: %s", strerror(errno));
      exit(1);
    }
    lg(Info, "bind port&ip success, bind: %d, errmsg: %s", bret, strerror(errno));
  }

  void Run(func_t func)
  {
    // std::cout << "run start" << std::endl;
    _isRuning = true;
    char buffer[size];
    while (_isRuning)
    {
      // 接收数据
      struct sockaddr_in info;
      socklen_t len = sizeof(info);

      ssize_t rcv = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&info, &len);

      if (rcv < 0)
      {
        lg(Warning, "recvfrom failed, err: %s", strerror(errno));
        continue;
      }
      // lg(Info, "recvfrom success, rcv: %d, errmdg: %s", rcv, strerror(errno));
      buffer[rcv] = 0;

      // 处理数据
      std::string sendmsg = func(buffer);
      // std::string sendmsg = "Client say# ";
      // sendmsg += buffer;
      // std::cout << sendmsg << std::endl;
      // 发送数据
      int sret = sendto(_socketfd, sendmsg.c_str(), sendmsg.size(), 0, (const sockaddr *)&info, len);
      if (sret < 0)
      {
        lg(Warning, "sendto message failed, err: %d, errmsg: %s", errno, strerror(errno));
        continue;
      }
      // lg(Info, "sendto message success, sret: %d, errmsg: %s", sret, strerror(errno));
    }
  }

  ~UdpServe()
  {
    close(_socketfd);
  }

private:
  int _socketfd;   // socket 文件描述符
  uint16_t _port;  // 端口号
  std::string _ip; // ip地址// 要接收任意地址的ip直接0.0.0.0
  bool _isRuning;
};